//
//  CBJUserAccountViewModel.swift
//  Weibo
//
//  Created by 崔健 on 16/5/22.
//  Copyright © 2016年 cbj. All rights reserved.
//

import UIKit

private let userInfoKey = "com.itheima.userInfoKey"

class CBJUserAccountViewModel: NSObject {

    
    static let sharedAccountViewModel = CBJUserAccountViewModel()
    
    var userAccount : CBJUserAccount?
    
    private override init() {
        
        super.init()
        userAccount = readAccountInfo()
    }
    
    var userLogin: Bool{
    
        if userAccount?.expires_date?.compare(NSDate()) == .OrderedDescending{
        
            return true
        }
        
        //如果过期  需要将 userAccount 设置为 nil
        userAccount = nil
        return false
    }
    
    
    func loadAccountToken(code : String , finished:(isSuccess: Bool)->()){
    
        
        CBJNetworkTools.sharedInstance.loadAccessToken(code) { (responseObject, error) in
            
            if error != nil{
            
                finished(isSuccess: false)
                return
            }
            
            // token获得成功 加载用户信息
            self.loadUserInfo(responseObject,finished: finished)
        }


    }
    
    func loadUserInfo(responseObj : AnyObject? , finished:(isSuccess: Bool)->()){

        guard let result = responseObj as? [String : AnyObject] else{
        
            return;
        }
        
        CBJNetworkTools.sharedInstance.loadUserInfo(result) { (responseObject, error) in
            
            if error != nil{
                
                
                finished(isSuccess: false)
                return;
            }
            
            guard var dict = responseObject as? [String : AnyObject] else{
                
                return;
            }
            
            for (key, value) in result {
                
                dict[key] = value
            }
            
            self.saveAccountInfo(dict)
            
            // 成功回调
            finished(isSuccess: true)
        }

     
    }
    
}

extension CBJUserAccountViewModel{

    
    
    func saveAccountInfo(dict : [String : AnyObject]) {
        
        let user = CBJUserAccount(dict: dict)
        
        userAccount = user
        
        let keys = ["access_token","expires_in","uid","name","avatar_large","expires_date"]
        let userDict = user.dictionaryWithValuesForKeys(keys)
        let userDefault = NSUserDefaults.standardUserDefaults()
        userDefault.setObject(userDict, forKey: userInfoKey)
        userDefault.synchronize()
    }
    
    func readAccountInfo() -> CBJUserAccount?{
    
        guard let dict = NSUserDefaults.standardUserDefaults().objectForKey(userInfoKey) as? [String : AnyObject] else{
        
            return nil
        }
        
        let userInfo = CBJUserAccount(dict: dict)
        
        return userInfo
    }
    
}



